package com.cryptoneedle.center.source.dolphin.config;


import com.cryptoneedle.center.config.helper.ConfigPropertyHelper;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class DolphinSchedulerClient {

    private final RestTemplate restTemplate;

    public DolphinSchedulerClient(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public <T> ClientResult<T> get(String path, Class<T> dataType) {
        String url = buildUrl(path);
        @SuppressWarnings("unchecked")
        ClientResult<T> result = restTemplate.getForObject(url, ClientResult.class);
        return result;
    }

    public <T> ClientResult<T> postJson(String path, Object body, Class<T> dataType) {
        String url = buildUrl(path);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> req = new HttpEntity<>(body, headers);
        @SuppressWarnings("unchecked")
        ClientResult<T> result = restTemplate.postForObject(url, req, ClientResult.class);
        return result;
    }

    public ClientResult<JsonNode> login(String userName, String userPassword) {
        // POST /login form urlencoded
        String url = buildUrl("/login");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> form = new LinkedMultiValueMap<>();
        form.add("userName", userName);
        form.add("userPassword", userPassword);
        HttpEntity<MultiValueMap<String, String>> req = new HttpEntity<>(form, headers);
        @SuppressWarnings("unchecked")
        ClientResult<JsonNode> result = restTemplate.postForObject(url, req, ClientResult.class);
        return result;
    }

    public ClientResult<JsonNode> getWorkflowStateCount(long projectCode) {
        String path = "/projects/analysis/workflow-state-count?projectCode=" + projectCode;
        @SuppressWarnings("unchecked")
        ClientResult<JsonNode> result = restTemplate.getForObject(buildUrl(path), ClientResult.class);
        return result;
    }

    private String buildUrl(String path) {
        String base = ConfigPropertyHelper.dsUrl();
        if (path.startsWith("/")) {
            return base + path;
        }
        return base + "/" + path;
    }
}